import json
import time
import traceback

import BiAn
import util


def monitor_15m_continuous_up(symbol='BTCUSDT',interval='15m',limit_var=10):
    # 获取最近10根K线数据
    df = BiAn.get_binance_data(limit_var=limit_var, symbol=symbol, interval=interval)
    # 生成列is_bull存储是否是阳线
    df['is_bull'] = df['close'] > df['open']
    # 倒转顺序
    df_reversed = df.reindex(index=df.index[::-1])
    is_bulls = df_reversed['is_bull'].values
    cnt = 0
    # 开始算连续几根阳
    for i in range(len(is_bulls) - 1):
        if is_bulls[i] :
            cnt +=1
        else:
            break
    print("最近连续阳线的次数:", cnt)
    zdf = 0
    # 计算连续阳线涨跌幅
    if cnt > 0:
        zdf = (float(df_reversed['close'].iloc[0]) - float(df_reversed['open'].iloc[cnt - 1])) / float(df_reversed['open'].iloc[cnt - 1]) * 100
        print("最近连续阳线的涨跌幅:", zdf)
    return cnt, zdf

# print(monitor_15m_continuous_up())

def monitor_symbol(symbol):
    try:
        cnt, zdf = monitor_15m_continuous_up(str(symbol))
        print(f"{symbol}连续阳线{cnt}次, 涨跌幅{zdf:.2f}%")
        # 6连阳就开始播放提示声
        if cnt > 5:
            util.play_voidce(f"{symbol}连续阳线{cnt}次, 涨跌幅{zdf:.2f}%")
        return True
    except Exception as e:
        print(e)
        print(traceback.format_exc())
        return False



if __name__ == '__main__':
    data = []
    with open('usdt.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
    mdata = []
    # 打印加载的数据
    print(data)
    min_sz = 10*100000000
    for i in data:
        # 市值大于5亿
        if i['shizhi'] > min_sz:
            mdata.append(i)
    print(f"市值大于{min_sz/100000000}亿的币数量:{len(mdata)}")
    while True:
        for i in mdata:
            monitor_symbol(i['symbol'] + "USDT")
            # 防止API限制
            time.sleep(1)
        # 5分钟循环一次
        time.sleep(60*5)
